<!-- pages/party/[type]/[id].vue -->
<template>
    <MainLayout :breadcrumbItems="breadcrumbItems" :neighbors="neighbors" :article="articleData"
        currentRoute="projects">
        <template #content>
            <article class="article-detail">

                <!-- 正文内容 -->
                <section class="article-content">
                    <div v-html="articleData.text"></div>
                </section>

                <!-- 附件下载 -->
                <div v-if="articleData.fileList.length>0" class="attachments">
                    <h3 style="font-size: 1rem;">相关附件</h3>
                    <ul>
                        <li v-for="file in articleData.fileList" :key="file.name">
                            <a :href="file.url" download target="_blank">{{ file.name }}</a>
                        </li>
                    </ul>
                </div>
            </article>
        </template>
        <template #footer>
            <div class="share" v-if="route.params.type === 'apply-for'">
                <div v-if="articleData.fileList[0]" class="btn" @click="downloadTemplate(articleData.fileList[0].url, articleData.fileList[0].name)">
                    活动申请</div>
                <div v-if="articleData.fileList[0]" class="btn submit">
                    <input type="file" @change="handleFileSelect" :disabled="isUploading" />
                    {{ isUploading ? '上传中...' : '提交申请' }}
                </div>
                <div class="download btn"
                    v-if="articleData.fileList[1]"
                    @click="downloadTemplate(articleData.fileList[1].url, articleData.fileList[1].name)">下载活动报告</div>
            </div>
        </template>
    </MainLayout>
</template>

<script setup>
//   import { format } from 'date-fns'
import MainLayout from '@/components/detailPage.vue'
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const { $fetchGov, $fetchAuth } = useNuxtApp()
const articleData = ref(null)
const isUploading = ref(false);
const customObj = ref({});

// 获取文章浏览次数
await $fetchGov(`/app/api/article/view/${route.params.id}`, { method: 'GET' })

// 获取文章数据
const { data: article, refresh: refreshArticle } = await useAsyncData(
    `projects-article-${route.params.id}`,
    async () => {
        const fetchMethod = userStore.user ? $fetchAuth : $fetchGov
        return await fetchMethod(`/app/api/article/${route.params.id}`, {
            method: 'GET'
        })
    },
    { watch: [() => route.params.id] }
)


watch(() => article.value.data?.formModelId, async (newId) => {
    if (newId) {
        const res = await $fetchAuth(`/app/api/core/form/${newId}`, {
            method: 'GET'
        })
        customObj.value = res.data;
    }
},
    {
        immediate: true,
        deep: true
    }
)

const downloadTemplate = async (fileUrl, name) => {
    try {
        const res = await $fetchAuth('/app/api/article/download-file/unrecorded', {
            method: 'POST',
            body: {
                url: fileUrl,
                name: name
            }
        })
        const url = window.URL.createObjectURL(res.data);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', name);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    } catch (error) {
        console.error('下载失败:', error);
    }
}

const handleFileSelect = (e) => {
    const selectedFile = e.target.files[0];
    if (!selectedFile) return;

    // 文件大小校验（1MB）
    if (selectedFile.size > 1048576) {
        uploadStatus.value = '文件大小超过限制';
        statusClass.value = 'error';
        return;
    }
    // 上传文件
    uploadFile(selectedFile);
}

const uploadFile = async (file) => {
    const formData = new FormData();
    formData.append('file', file);
    isUploading.value = true;
    try {
        const res = await $fetchAuth('/app/api/upload/file-upload', {
            method: 'POST',
            body: formData
        });
        //提交申请
        submitApply(res.data);
    } catch (error) {
        isUploading.value = false;
        console.error('上传失败:', error);
    }
}

const submitApply = async (data) => {
    isUploading.value = false;
    try {
        const fileArr = [];
        fileArr.push(data);
        const res = await $fetchAuth(`${customObj.value.submitPath}`, {
            method: 'POST',
            body: {
                formId: article.value.data?.formModelId,
                articleId: article.value.data.id,
                file: fileArr,
            }
        })
        if (res.data.status === 0) {
            ElMessage.success('申请提交成功');
        }
    } catch (error) {
        console.error('提交失败:', error);
    }
}

// 添加路由变化监听
watch(() => route.params.id, async (newId) => {
    if (newId) {
        await refreshArticle()
    }
})

articleData.value = article.value.data

const { data: prev } = await useAsyncData(
    `projects-prev`,
    async () => {
        return await $fetchGov(`/app/api/article/prev`, {
            method: 'GET',
            params: { id: route.params.id, channel: route.params.type, order: articleData.value?.order },
        })
    }
)

const { data: next } = await useAsyncData(
    `projects-next`,
    async () => {
        return await $fetchGov(`/app/api/article/next`, {
            method: 'GET',
            params: { id: route.params.id, channel: route.params.type, order: articleData.value?.order },
        })
    }
)

const neighbors = computed(() => {
    return {
        prev: prev.value.data && prev.value.data.id ? {
            id: prev.value.data.id,
            title: prev.value.data.title,
            nav: 'projects',
            category: route.params.type
        } : null,
        next: next.value.data && next.value.data.id ? {
            id: next.value.data.id,
            title: next.value.data.title,
            nav: 'projects',
            category: route.params.type
        } : null
    }
})

// 面包屑导航
const breadcrumbItems = computed(() => [
    { title: '首页', path: '/' },
    { title: '健康项目', path: '/projects' },
    {
        title: route.params.type === 'current' ? '当前项目' : route.params.type === 'poverty' ? '往期项目' : '项目申请',
        path: `/projects/${route.params.type}`
    },
    { title: article.value.data.title }
])


// SEO优化
useHead({
    // title: `${article.value.title} - 云南省健康与发展研究会`,
    meta: [
        {
            name: 'description',
            // content: article.value.summary || article.value.title
        },
        {
            property: 'og:image',
            // content: article.value.cover || '/images/og-default.png'
        }
    ]
})
</script>

<style lang="scss" scoped>
@use '@/assets/scss/main' as *;

.article-detail {

    .article-content {
        line-height: 1.8;
        font-size: 1.1rem;

        ::v-deep(img) {
            max-width: 100%;
            height: auto;
            margin: 1rem 0;
            border-radius: 4px;
        }

        ::v-deep(table) {
            width: 100%;
            margin: 1rem 0;
            border-collapse: collapse;

            td,
            th {
                padding: 0.8rem;
                border: 1px solid #ddd;
            }
        }
    }

    .attachments {
        margin-top: 3rem;
        padding-top: 1rem;
        // border-top: 1px solid #eee;

        h3 {
            color: #333;
            margin-bottom: .2rem;
        }

        li {
            padding: 0.5rem 0;
            list-style-type: none;

            a {
                color: #1867CA;
                text-decoration: none;
                display: flex;
                align-items: center;

                &:hover {
                    text-decoration: underline;
                }
            }
        }
    }

    .article-actions {
        margin-top: 3rem;
        padding-top: 2rem;
        border-top: 1px solid #eee;
        text-align: center;
    }
}

.share {
    color: $myprimary-color;
    display: flex;
    gap: 1rem;

    .btn {
        background: rgba(24, 103, 202, .1);
        font-size: .8rem;
        padding: .3rem 1rem;
        border-radius: 3px;
        cursor: pointer;

        &.download {
            background: $myprimary-color;
            color: #fff;
        }

        &.submit {
            position: relative;

            input {
                position: absolute;
                cursor: pointer;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                opacity: 0;
            }
        }
    }
}

.gov-button {
    display: inline-flex;
    align-items: center;
    padding: 0.8rem 1.5rem;
    background: #1867CA;
    color: white;
    border-radius: 4px;
    text-decoration: none;
    transition: opacity 0.2s;

    &:hover {
        opacity: 0.9;
    }
}

@media (max-width: 768px) {
    .article-detail {
        padding: 0;
    }
}
</style>